package interview.algorithms.again_in_interview.concurrent;

/**
 * @author fance
 * @date 2018/8/22 16:17
 */
public class PrintOneTwo implements Runnable{
    // 打印次数
    private static final int PRINT_COUNT = 10;
    // 前一个线程的打印锁
    private final Object fontLock;
    // 本线程的打印锁
    private final Object thisLock;
    // 打印字符
    private final char printChar;

    public PrintOneTwo(Object fontLock, Object thisLock, char printChar) {
        this.fontLock = fontLock;
        this.thisLock = thisLock;
        this.printChar = printChar;
    }

    @Override
    public void run() {
        for (int i = 0; i < PRINT_COUNT; i++) {
            synchronized (fontLock) {

                synchronized (thisLock) {
                    System.out.println(printChar);
                    thisLock.notifyAll();
                }
                if (i < PRINT_COUNT - 1) {
                    try {
                        fontLock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    public static void main(String[] args) {
        Object lock1 = new Object();
        Object lock2 = new Object();

        Thread thread1 = new Thread(new PrintOneTwo(lock2,lock1,'1'));
        Thread thread2 = new Thread(new PrintOneTwo(lock1,lock2,'2'));
        thread1.start();
        thread2.start();
    }
}
